'''
    第二章习题
'''
'''
    第一题
'''
# class Student(object):
#     count = 0
#     def __init__(self, name):
#         self.name = name
#         Student.count += 1
#
# stu1 = Student('ss')
# print(Student.count)
# stu2 = Student('ee')
# print(Student.count)
# stu3 = Student('tt')
# print(Student.count)

'''
    第二题
'''
# import time
# def metric(fn):
#     def run_time(*args, **kw):
#         start_time = time.time()
#         fn(*args, **kw)
#         end_time = time.time()
#         print('耗时：{:.4f}s'.format(end_time - start_time))
#     return run_time
#
# @metric
# def sum():
#     s = 0
#     for i in range(0,100000):
#         s = s + i
#     print('sum = %d' % s)
#
# sum()

'''
    第三题
'''
import sys
import os
import time
import threading
#import termios
#import tty
import cv2
import pyprind

class CharFrame:

    ascii_char = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "

    # 像素映射到字符
    def pixelToChar(self, luminance):
        return self.ascii_char[int(luminance/256*len(self.ascii_char))]

    # 将普通帧转为 ASCII 字符帧
    # limitSize 参数接受一个元组，表示图片的限宽限高。
    # fill 表示是否用空格填充图片宽度至限宽，wrap 表示是否在行末添加换行符
    def convert(self, img, limitSize=-1, fill=False, wrap=False):
        if limitSize != -1 and (img.shape[0] > limitSize[1] or img.shape[1] > limitSize[0]):
            img = cv2.resize(img, limitSize, interpolation=cv2.INTER_AREA)
        ascii_frame = ''
        blank = ''
        if fill:
            blank += ' '*(limitSize[0]-img.shape[1])
        if wrap:
            blank += '\n'
        for i in range(img.shape[0]): # shape 为元组 图片的（宽，高）
            for j in range(img.shape[1]):
                ascii_frame += self.pixelToChar(img[i,j])
            ascii_frame += blank
        return ascii_frame

class I2Char(CharFrame):

    result = None

    def __init__(self, path, limitSize=-1, fill=False, wrap=False):
        self.genCharImage(path, limitSize, fill, wrap)

    def genCharImage(self, path, limitSize=-1, fill=False, wrap=False):
        # 读取图片
        frame = cv2.cvtColor(cv2.imread(path, cv2.IMREAD_COLOR), cv2.COLOR_BGR2GRAY)
        # 给self.result 字符画字符串赋值
        self.result = self.convert(frame, (100,80), wrap=True)


    def show(self, stream = 2):
        if self.result is None:
            return
        if stream == 1 and os.isatty(sys.stdout.fileno()):
            self.streamOut = sys.stdout.write
            self.streamFlush = sys.stdout.flush
        elif stream == 2 and os.isatty(sys.stderr.fileno()):
            self.streamOut = sys.stderr.write
            self.streamFlush = sys.stderr.flush
        elif hasattr(stream, 'write'):
            self.streamOut = stream.write
            self.streamFlush = stream.flush
        self.streamOut(self.result)
        self.streamFlush()
        self.streamOut('\n')


if __name__ == '__main__':
    import argparse
    # 设置命令行参数
    parser = argparse.ArgumentParser()
    parser.add_argument('file',
                        help='Video file or charvideo file')
    parser.add_argument('-e', '--export', nargs = '?', const = 'charvideo.txt',
                        help='Export charvideo file')
    # 获取参数
    args = parser.parse_args()
    #v2char = V2Char(args.file)
    # 如果有.txt字符动画文件，就直接导入
    #if args.export:
    #    v2char.export(args.export)
    # 否则正常转码播放
    #v2char.play()

    '''
        通过命令行调用图片转字符画功能 ,命令行执行 Python v2char.py t3.jpeg,输出字符画
    '''
    i2char = I2Char(args.file)
    i2char.show()